<?php

namespace api\upload\driver;

use api\upload\exception\UploadException;
use think\File;

class Local extends Upload
{
    public string $uploadDir = '';
    public array $uploadConfig;
    private array $config;

    /**
     * @param array $uploadConfig 上传配置
     * @param string $dir 保存目录
     * @throws UploadException
     */
    public function __construct(array $uploadConfig, string $dir = '')
    {
        $this->uploadConfig = $uploadConfig;
        $this->uploadDir = $dir;
        $this->config = $uploadConfig;
        if (empty($this->config)) {
            throw new UploadException('参数未配置');
        }
    }


    /**
     * 获取域名
     *
     * @return string
     */
    public function getDomain(): string
    {
        if (isset($this->config['local']) && isset($this->config[$this->uploadConfig['upload_type']]['domain']) && $this->config[$this->uploadConfig['upload_type']]['domain']) {
            $domain = $this->config[$this->uploadConfig['upload_type']]['domain'];
        } else {
            $http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off') ? 'https' : 'http';
            $domain = $http . '://' . $_SERVER['HTTP_HOST'];
        }

        if (!strstr($domain, 'http')) {
            $domain = 'http://' . $domain;
        }

        return rtrim($domain, '/') . config('filesystem.disks.public.url') . '/';
    }

    /**
     * 上传图片文件
     *
     * @param File $uploadFileInfo 文件信息
     * @return array
     * @throws UploadException
     */
    public function uploadImageFile(File $uploadFileInfo, string $fileName = ''): array
    {
        try {
            $fileName = \think\facade\Filesystem::disk('public')->putFile(rtrim($this->uploadDir, '/'), $uploadFileInfo, $fileName ? function () use ($fileName) {
                $fileName = explode('.', $fileName);
                return $fileName[0];
            } : 'sha1');
            $saveName = str_replace('\\', '/', $fileName);

            return [
                'uploadPath' => ltrim(config('filesystem.disks.public.url') . '/' . $saveName, '/'),
                'showPath' => $this->getDomain() . $saveName
            ];
        } catch (\think\exception\ValidateException $e) {
            throw new UploadException($e->getError());
        }
    }

    /**
     * 上传文件
     *
     * @param File $uploadFileInfo 文件信息
     * @return array
     * @throws UploadException
     */
    public function uploadFile(File $uploadFileInfo): array
    {
        try {
            $fileName = \think\facade\Filesystem::disk('public')->putFile(rtrim($this->uploadDir, '/'), $uploadFileInfo, 'sha1');
            $saveName = str_replace('\\', '/', $fileName);

            return [
                'uploadPath' => ltrim(config('filesystem.disks.public.url') . '/' . $saveName, '/'),
                'showPath' => $this->getDomain() . $saveName
            ];
        } catch (\think\exception\ValidateException $e) {
            throw new UploadException($e->getError());
        }
    }

    /**
     * 上传本地文件
     *
     * @param string $localFilePath 本地文件地址
     * @return array
     * @throws UploadException
     */
    public function uploadLocalFile(string $localFilePath): array
    {
        try {
            $file = new File($localFilePath);
            $fileName = \think\facade\Filesystem::disk('public')->putFile(rtrim($this->uploadDir, '/'), $file, 'sha1');

            $saveName = str_replace('\\', '/', $fileName);

            return [
                'uploadPath' => ltrim(config('filesystem.disks.public.url') . '/' . $saveName, '/'),
                'showPath' => $this->getDomain() . $saveName
            ];
        } catch (\think\exception\ValidateException $e) {
            throw new UploadException($e->getError());
        }
    }

    /**
     * 删除文件
     *
     * @param string $filePath 文件地址
     * @return bool
     */
    public function deleteFile(string $filePath): bool
    {
        if (!file_exists($filePath)) {
            return true;
        }
        try {
            return unlink($filePath);
        } catch (\Exception $e) {
            exception_log('本地上传文件删除失败', $e, false);
            return false;
        }
    }
}
